<template>
  <div>
    <div class="padding-tb">
      <el-button type="primary" size="mini" @click="showForm">添加管理员</el-button>
    </div>
    <div>
      <el-table :data="data.list" border stripe>
        <el-table-column prop="username" align="center" label="登录账号" width="100"></el-table-column>
        <el-table-column prop="level" align="center" label="权限级别" width="100" :formatter="levelFormatter"></el-table-column>
        <el-table-column prop="lastLoginAt" align="center" :formatter="timeFormatter" label="上次登录时间" width="280"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip content="不能操作自己以及级别比自己高的用户" :disabled="scope.row.username!=username">
            <el-dropdown @command="setLevel($event,scope.row.username)">
              <el-button type="primary" size="mini" :disabled="scope.row.username==username || scope.row.level > level">
                  设置权限级别<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>              
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item 
                  v-for="(value,key) of levelMap" 
                  :key="key" 
                  v-if="key<=level" 
                  :command="key"
                >{{value}}</el-dropdown-item>
            </el-dropdown-menu>
            </el-dropdown>
            </el-tooltip>
            <el-tooltip content="不能操作自己以及级别比自己高的用户" :disabled="scope.row.username!=username">
            <el-button type="primary" size="mini" :disabled="scope.row.username==username || scope.row.level > level" @click="resetPwd(scope.row.username)">重置密码</el-button>
            </el-tooltip>
            <el-tooltip content="不能操作自己以及级别比自己高的用户" :disabled="scope.row.username!=username">
            <el-button type="danger" size="mini" :disabled="scope.row.username==username || scope.row.level > level" @click="remove(scope.row.username)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="padding-tb">
      <el-pagination
      @size-change="pageSizeChange"
      @current-change="pageNoChange"
      :current-page="pageNo"
      :page-sizes="[10, 20, 30, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total">
      </el-pagination>
    </div>

    <el-dialog title="添加管理员" width="500px" :visible.sync="adminFormShow">
        <el-form :model="adminForm" ref="adminForm" :rules="adminFormRules">
            <el-form-item label="账号" :label-width="formLabelWidth" prop="username">
              <el-input v-model="adminForm.username" 
                  type="text" 
                  clearable 
                  autocomplete="off" 
                  @keypress.enter.native="adminSubmit"
                  placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="账号类型" :label-width="formLabelWidth" prop="level">
              <el-select v-model="adminForm.level" placeholder="请选择账号类型">
                <el-option
                  v-for="(label, value) of levelMap"
                  :key="value"
                  :label="label"
                  :value="value"
                  :disabled="value>level">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
              <el-input v-model="adminForm.password" 
                  type="password" 
                  clearable 
                  autocomplete="off" 
                  @keypress.enter.native="adminSubmit"
                  placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" 
              :label-width="formLabelWidth" prop="confirmPassword">
              <el-input v-model="adminForm.confirmPassword" 
                  type="password" 
                  clearable 
                  autocomplete="off" 
                  @keypress.enter.native="adminSubmit"
                  placeholder="请输入确认密码"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="adminFormShow = false">取 消</el-button>
            <el-button type="primary" @click="adminSubmit">保 存</el-button>
        </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from "vuex";
let levelMap = {1:'普通管理员',2:'DKP管理员',3:'超级管理员'}
import { adminAdd, adminList, adminSetLevel, adminResetPwd, adminChangePwd, adminRemove } from "../service/api";
export default {
  computed: {
    ...mapGetters(['level','username'])
  },
  data() {
    return {
      data: {
        list: [],
        total: 0
      },
      pageNo: 1,
      pageSize: 10,
      levelMap,
      formLabelWidth: "100px",
      adminFormShow: false,
      adminForm: {
        username: '',
        password: '',
        confirmPassword: '',
        level: ''
      },
      adminFormRules: {
        username: [{required: true, message: "请输入账号", trigger: "blur"}],
        level: [{required: true, message: "请选择账号类型", trigger: "blur"}],
        password: [{required: true, message: "请输入密码", trigger: "blur"}],
        confirmPassword: [
          {required: true, message: "请输入确认密码", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if(value != this.adminForm.password){
                callback(new Error('两次输入密码不一致!'));
              }else{
                callback();
              }
            }
          }
        ]
      }
    };
  },
  methods: {
    showForm() {
      this.$refs.adminForm && this.$refs.adminForm.resetFields();
      this.adminFormShow = true;
    },
    adminSubmit() {
      this.$refs["adminForm"].validate(valid => {
        if (valid) {
          adminAdd(this.adminForm).then(
            ({ data }) => {
              this.refreshData();
            }
          );
        }
      });
    },
    levelFormatter(v) {
      return levelMap[v.level]
    },
    timeFormatter(v) {
      // console.log(v)
      if(!v.lastLoginAt){
        return '';
      }
      v = new Date(v.lastLoginAt)
      let year = v.getFullYear(),
          month = ('0' + (v.getMonth() + 1)).slice(-2),
          day = ('0' + v.getDate()).slice(-2),
          hour = ('0' + v.getHours()).slice(-2),
          minute = ('0' + v.getMinutes()).slice(-2),
          second = ('0' + v.getSeconds()).slice(-2)
      return `${year}年${month}月${day}日${hour}:${minute}:${second}`
    },
    pageSizeChange(val) {
      this.fetchData(1, val);
    },
    pageNoChange(val) {
      this.fetchData(val, this.pageSize);
    },
    refreshData() {
      this.fetchData(this.pageNo,this.pageSize);
    },
    fetchData(pageNo = 1, pageSize = 10) {
      this.pageNo = pageNo,
      this.pageSize = pageSize
      adminList({
        pageNo,
        pageSize
      }).then(({data}) => {
        this.data = data.data;
      })
    },
    setLevel(level, username) {
      adminSetLevel({level,username}).then(({data}) => {
        this.$message({
          showClose: true,
          message: "权限设置成功",
          type: "success"
        });
        this.refreshData();
      })
    },
    resetPwd(username) {
      this.$confirm(`确定要重置用户【${username}】的密码吗？`,'提示信息').then(_=>{
        adminResetPwd({username}).then(({data})=>{
          this.$alert(`密码已重置为【${data.data.newPwd}】,请该用户登录后立刻修改密码`, '提示信息', {
            closeOnClickModal: true
          });
        })
      })
    },
    remove(username) {
      this.$confirm(`确定要删除用户【${username}】吗？`,'提示信息').then(_=>{
        adminRemove({username}).then(_=>{
          this.$message({
            showClose: true,
            message: "删除成功！",
            type: "success"
          });
          this.refreshData();
        })
      })
    }
  },
  created() {
    this.fetchData();
  }
};
</script>

<style lang="less" scoped>
.padding-tb {
  padding: 10px 0;
}
</style>
